var app = getApp();
import commonAPI from '../../api/api'
import integralAPI from '../../api/integralAPI'
const FN = require('../../utils/public');
var plugin = requirePlugin("ihearing-eval");// 智聆口语测评（腾讯免费）
let plugin4SEO = requirePlugin("myPlugin");//  智聆语音测评（腾讯付费）
let manager = plugin.getRecordRecognitionManager();
var ba = wx.getBackgroundAudioManager();
Page({
  data: {
    errorwordsObj: {},
    paramsErrorWords: [],
    usplaygif: 'horn.png',
    ukplaygif: 'horn.png',
    sto: 0,
    loaddingOver: false,
    testResult: {},
    secondReading: 0,
    pageparam: {
      "playorstop": "stop",
      "btnStatus": 0,
      "btnIcon": "playIcon.png",
      "second": 0
    },
    phonemeArr: [],
    collWordArr: [],
    errorwordsIndex: 0,
    evaluationType: '1',// 口语测评模式，1：智聆口语测评（腾讯免费），2：智聆语音测评（腾讯付费），默认1
    integralObj:{},// 积分对象
    pointsConfig: {},// 翻译積分配置
    pointsConfig4AIErrorCorrection: {},// AI纠音積分配置
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    wx.hideShareMenu(); // 禁止分享
    var errorwordsObj = JSON.parse(options.errorwords);
    if (errorwordsObj) {
      that.setData({
        paramsErrorWords: errorwordsObj.errWords,
        integralObj:app.globalData.userInfo.integralObj
      })
    }
    this.initOthderData();
    
  },

  /*
 1. 设置app屏幕的高度
 2. 获取微信小程序信息->设置当前纠音模型
 3. 获取积分配置
 */
  initOthderData() {
    // 微信用户信息
    // app.callback4MiniappInfo = miniappInfo => {
    //   this.setData({
    //     evaluationType: miniappInfo.miniappInfoModel
    //   })
    // }

    const item = app.globalData.miniappInfo.pointsconfigList.find(item=>item.pointsConfigKey == 'translateLowScoreWords');
    const item4AIErrorCorrection = app.globalData.miniappInfo.pointsconfigList.find(item=>item.pointsConfigKey == 'AIErrorCorrection');
    this.setData({
      evaluationType: app.globalData.miniappInfo.miniappInfoModel,
      pointsConfig:item,
      pointsConfig4AIErrorCorrection:item4AIErrorCorrection
    })

    if(app.globalData.userInfo.integralObj.integralNum<this.data.pointsConfig.pointsConfigValue || app.globalData.userInfo.integralObj.integralNum==null){
      this.navigateToPointsPageForVideo(app.globalData.userInfo.integralObj.integralNum);
      return;
    }
    this.translation();
  },

  // 翻译
  translation: function () {
    var that = this;
    const words = that.data.paramsErrorWords[that.data.errorwordsIndex].errorWords;
    commonAPI.vsTranslation({ 
      words:words.trim(),
      translationRecordReq:{
        translationRecordPlatform:'有道翻译',
        voiceSystemId:that.data.paramsErrorWords[that.data.errorwordsIndex].vsId,
        translationRecordTarget:words.trim(),
       translationRecordType:'1',
      }
    }).then(res => {
      if (res.code == '200') {
        let errorwordsObj = typeof res.data.resultJson == 'object' ? res.data.resultJson : JSON.parse(res.data.resultJson);
        if(res.data.deductPoints == 'true'){
          that.handlePerformLowScoreWordExercise();
        }
        var wordcount = "errorwordsObj.wordcount";
        that.setData({
          errorwordsObj,
          [wordcount]: res.data.wordcount,
          loaddingOver: true
        });
      }
    })
  },

  // 翻译消耗积分
  handlePerformLowScoreWordExercise(){
    let that = this;
    integralAPI.performLowScoreWordExercise({
      integralId:app.globalData.userInfo.integralObj.integralId,
      integraldetail:{
        integralId:app.globalData.userInfo.integralObj.integralId,
        integralDetailType:that.data.pointsConfig.pointsConfigType,
        integralDetailDesc:that.data.pointsConfig.pointsConfigName,
        integralDetailNum:that.data.pointsConfig.pointsConfigType === "1" ? that.data.pointsConfig.pointsConfigValue : -that.data.pointsConfig.pointsConfigValue
      }
     }).then(res => {})
  },

  // AI纠音消耗积分 
  doPointsConfig4AIErrorCorrection(){
    var that = this;
    integralAPI.performLowScoreWordExercise({
      integralId:app.globalData.userInfo.integralObj.integralId,
      integraldetail:{
        integralId:app.globalData.userInfo.integralObj.integralId,
        integralDetailType:that.data.pointsConfig4AIErrorCorrection.pointsConfigType,
        integralDetailDesc:that.data.pointsConfig4AIErrorCorrection.pointsConfigName,
        integralDetailNum:that.data.pointsConfig4AIErrorCorrection.pointsConfigType === "1" ? that.data.pointsConfig4AIErrorCorrection.pointsConfigValue : -that.data.pointsConfig4AIErrorCorrection.pointsConfigValue
      }
     }).then(res => {})
  },

  // 英式发音
  ukVoice: function (e) {
    var index = e.target.dataset.index;
    this.setData({
      ukplaygif: "playGif.gif",
    })
    this.speech("uk-speech", index);
  },

  // 美式发音
  usVoice: function (e) {
    var index = e.target.dataset.index;
    this.setData({
      usplaygif: "playGif.gif",
    })
    this.speech("us-speech", index);
  },

  speech: function (s, index) {
    var that = this;
    ba.src = that.data.errorwordsObj.basic[s];
    ba.title = that.data.errorwordsObj.query;
    ba.coverImgUrl = "";
    ba.onPlay(function () {

    })

    // 监听播放是否已经结束
    ba.onEnded(function () {
      that.setData({
        ukplaygif: "horn.png",
        usplaygif: "horn.png"
      })
    })

    // 监听背景音频停止事件
    ba.onError(function () {
      that.setData({
        ukplaygif: "horn.png",
        usplaygif: "horn.png"
      })
    })

    // 监听背景音频暂停事件
    ba.onPause(function () {
      that.setData({
        ukplaygif: "horn.png",
        usplaygif: "horn.png"
      })
    })

    // 监听背景音频停止事件
    ba.onStop(function () {
      that.setData({
        ukplaygif: "horn.png",
        usplaygif: "horn.png"
      })
    })
  },
  
  // 按住
  starFollowup: function (e) {
    var that = this;
    if(this.data.integralObj.integralNum<this.data.pointsConfig4AIErrorCorrection.pointsConfigValue){
      this.navigateToPointsPageForVideo(this.data.integralObj.integralNum);
        return ;
    }
    wx.showLoading({
      title: '录音中......',
      mask: false
    });
    var second = "pageparam.second";
    that.setData({
      [second]: 1,
    })
    that.cutTime();
    this.stopVoice();
  },

   // 暂停原文
   stopVoice: function (e) {
    var that = this;
    var btnIcon = "pageparam.btnIcon"
      that.setData({
        [btnIcon]: 'playIcon.png',
        ukplaygif: "horn.png",
        usplaygif: "horn.png"
      })
    ba.pause();
  },

  // 定时器
  cutTime: function () {
    var that = this;
    var s, i = 0;
    s = setInterval(function () {
      i++;
      that.setData({
        secondReading: i,
      })
    }, 1000);
    that.setData({
      sto: s,
    });
  },

  // 松开
  endFollowup: function (e) {
    var that = this;
    manager.stop();
    clearInterval(that.data.sto);
    wx.hideLoading();
  },

  // next
  nextWords: function () {
    var that = this;
    if (that.data.errorwordsIndex < (that.data.paramsErrorWords.length - 1)) {
      that.setData({
        errorwordsIndex: ++that.data.errorwordsIndex
      });
      that.againRepeat();
      that.translation();
    } else {
      FN.Toast('已经到最后了')
    }
  },

  // 重录
  againRepeat: function () {
    var btnStatus = "pageparam.btnStatus"
    var btnIcon = "pageparam.btnIcon"
    this.setData({
      [btnStatus]: 0,
      secondReading: 0,
      [btnIcon]: 'playIcon.png'
    })
  },

  // 收藏英语单词
  collWord: function (e) {
    var that = this,
      collectionContent = e.currentTarget.dataset.word, wordcount = "errorwordsObj.wordcount";
    commonAPI.colSaveCol({
      collectionContent: collectionContent,
      voiceSystemId: that.data.paramsErrorWords[that.data.errorwordsIndex].voiceSystemId,
      collectionType: "2"
    }).then(res => {
      if (res.code == '200') {
        that.setData({
          [wordcount]: 1,
        })
        FN.Toast("收藏成功");
      }
    })
  },

  // 取消收藏
  delWord: function (e) {
    var that = this, wordcount = "errorwordsObj.wordcount",
      collectionContent = e.currentTarget.dataset.word;
    commonAPI.colDelCol({ collectionContent: collectionContent }).then(res => {
      if (res.code == '200') {
        that.setData({
          [wordcount]: 0
        })
        FN.Toast(res.data);
      }
    })
  },

  // 播放自己的录音
  playMyvoice: function () {
    var that = this;
    this.innerAudioContext = wx.createInnerAudioContext();
    this.innerAudioContext.onError((res) => {
      // 播+放音频失败的回调
    })
    this.innerAudioContext.src = this.data.scoreDetail.tempFilePath; // 这里可以是录音的临时路径
    this.innerAudioContext.play();
    that.innerAudioContext.onPlay(function () {
      var btnIcon = "pageparam.btnIcon"
      that.setData({
        [btnIcon]: 'stopBtn4errorword.png'
      })
    });

    // 音频暂停回调
    that.innerAudioContext.onStop(function () {

    });

    // 音频结束回调
    that.innerAudioContext.onEnded(function () {
      var btnIcon = "pageparam.btnIcon"
      that.setData({
        [btnIcon]: 'playIcon.png'
      })
    });
  },

  // 去练句子 vrNewestvr
  voiceRepeat: function (e) {
    var that = this,
      voiceArr = new Array();
    commonAPI.vrNewestvr({ voiceSystemId: that.data.paramsErrorWords[that.data.errorwordsIndex].voiceSystemId }).then(res => {
      if (res.code == '200') {
        voiceArr.push(res.data[0]);
        wx.navigateTo({
          url: '../homeworkrepeat/homeworkrepeat',
          events: {
            acceptDataFromOpenedPage: function (data) {
              console.log(data)
            },
            someEvent: function (data) {
              console.log(data)
            }
          },
          success: function (res) {
            res.eventChannel.emit('acceptDataFromOpenerPage', { scene: that.data.paramsErrorWords[that.data.errorwordsIndex].voiceSystemId, getIntoType: 'other' })
          }
        })
      }
    })
  },

  // 测评模式切换
  onChange4evaluationType(event) {
    this.setData({
      evaluationType: event.detail
    });
    this.initManagerModel();
  },

  // 初始化测评模型
  initManagerModel() {
    if (this.data.evaluationType == '1') {
      manager = plugin.getRecordRecognitionManager()// 智聆口语测评
    } else {
      this.initTengxunSOE();// 腾讯云智聆语音测评初始化
    }
  },

  // 初始化智聆语音测评（收费模式）
  initTengxunSOE() {
    var that = this;
    commonAPI.getFederationToken({}).then(res => {
      if (res.code == '200') {
        var obj = JSON.parse(res.data)
        var data = obj.Credentials;
        manager = plugin4SEO.getSoeRecorderManager({
          getAuthorization: function (callback) {
            callback({
              TmpSecretId: data.TmpSecretId,
              TmpSecretKey: data.TmpSecretKey,
              Token: data.Token
            });
          }
        });
        manager.onStart((res) => {
          console.log("成功开始录音识别", res)
        });

        /*
        识别结束事件,获取拿到音频数据
        1. 识别结束后，有*，需要处理。
        */
        manager.onStop((res) => {
          console.log("识别结束事件", res)
          that.setData({
            tempFile: res
          });
        })

        manager.onSuccess((res) => {
          console.log('打印识别结果', res)
          if (res.Status == "Finished") {
            that.doPointsConfig4AIErrorCorrection();
            clearInterval(that.data.sto);
            var btnStatus = "pageparam.btnStatus"
            var second = "pageparam.second";
            that.setData({
              testResult: res,
              [btnStatus]: 2,
              [second]: 0,
              phonemeArr: res.Words[0].hasOwnProperty("PhoneInfos") ? res.Words[0].PhoneInfos : null,
              currentScore: parseInt(res.PronAccuracy),
              scoreDetail: res,
            })
          }
        })

        manager.onError((res) => {
          //打印错误
          console.log('打印错误', res)
          // FN.Toast(res.Response.Error.Message);
          manager.stop();
        })
      }
    });
  },

  // 智聆口语测评（免费模式）
  freeEvaluation() {
    var that = this;
    manager.onStart = function (res) { // 正常开始录音识别时会调用此事件
      console.log("成功开始录音识别", res);
    }
    // 识别结束事件
    manager.onStop = function (res) {
      that.doPointsConfig4AIErrorCorrection();
      clearInterval(that.data.sto);
      var btnStatus = "pageparam.btnStatus"
      var second = "pageparam.second";
      that.setData({
        testResult: res,
        [btnStatus]: 2,
        [second]: 0,
        phonemeArr: res.result.words[0].hasOwnProperty("phone_info") == true ? res.result.words[0].phone_info : null,
        currentScore: parseInt(res.result.pron_accuracy),
        scoreDetail: res,
      })
    }
    manager.onError = function (res) { // 异常回调
      FN.Toast(res.msg);
      manager.stop();
      // 20802 小程序请求频率限制,
      if (res.retcode == 20802) {
        let promise = FN.Confirm(`AI测评打分高分期，需要切换到智聆语音测评AI模型，是否确认切换`);
        promise.then(res => {
          that.setData({
            evaluationType: '2'
          });
          that.updateAImodel();// 更改AI纠音模型
          that.initManagerModel();// 切换AI纠音模型
        }).catch(res => {

        });
      }
    }
  },
  
  // 录音
  followup: function () {
    if (this.data.evaluationType == '1') {
      this.freeEvaluation()// 监听录音
      this.initStartOption4free();// 开始录音识别
    } else {
      this.initStartOption4SOE();// 开始录音识别
    }
  },

    // 录音配置(soe模式)
    initStartOption4SOE() {
      const words = this.data.paramsErrorWords[this.data.errorwordsIndex].errorWords    
      const options4SOE = {
        content: words,
        evalMode:0,// 0：词模式（中文评测模式下为文字模式），1：句子模式，2：段落模式，3：自由说模式，当为词模式评估时
        duration: 60000,
        scoreCoeff: 3, // [1.0 - 4.0] 范围内的浮点数，用于引擎评分的严格程度
        serverType: 0,// 评估语言，0：英文，1：中文。
        textMode: 0,// 输入文本模式，0: 普通文本，1: 音素结构文本      
      }
      manager.start(options4SOE); // 开始识别
    },

  // 录音配置(免費模式)
  initStartOption4free() {
    const words = this.data.paramsErrorWords[this.data.errorwordsIndex].errorWords    
    console.log(words);
    const options = {
      duration: 60000,
      content: words,
      evalMode: 'word', // 单词模式
      scoreCoeff: 3
    }
    manager.start(options); // 开始识别
  },
  
// 跳转观看视频获取积分页面
navigateToPointsPageForVideo(integralNum){
  let promise = FN.Confirm(`积分不足，无法翻译，当前积分：${integralNum?integralNum:0}，看视频可以获取积分，是否观看？`);
  promise.then(res => {
    wx.navigateTo({
      url: '../myIntegral/myIntegral'
    })
  }).catch(res => {

  });
},
  onShow: function (res) {
    this.initManagerModel();
  }
})